home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / print / pr.zip / GETOPT.C < prev    next >
C/C++ Source or Header  |  1986-08-13  |  2KB  |  86 lines

  1. /*LINTLIBRARY*/
  2. #define NULL    0
  3. #define EOF    (-1)
  4. #ifndef NAME
  5. #define NAME    "options"
  6. #endif
  7. /*
  8. #define ERR(s, c)    if(opterr){\
  9.     extern int strlen(), write();\
  10.     char errbuf[2];\
  11.     errbuf[0] = c; errbuf[1] = '\n';\
  12.     (void) write(2, argv[0], (unsigned)strlen(argv[0]));\
  13.     (void) write(2, s, (unsigned)strlen(s));\
  14.     (void) write(2, errbuf, 2);}
  15. */
  16.  
  17. extern int strcmp();
  18. extern char *index();
  19.  
  20. int    opterr = 1;
  21. int    optind = 1;
  22. int    optopt;
  23. char    *optarg;
  24.  
  25. int
  26. getopt(argc, argv, opts)
  27. int    argc;
  28. char    **argv, *opts;
  29. {
  30.     static int sp = 1;
  31.     register int c;
  32.     register char *cp;
  33.  
  34.     if(sp == 1)
  35.         if(optind >= argc ||
  36.            argv[optind][0] != swchar() || argv[optind][1] == '\0')
  37.             return(EOF);
  38.         else if(strcmp(argv[optind], "--") == NULL) {
  39.             optind++;
  40.             return(EOF);
  41.         }
  42.     optopt = c = argv[optind][sp];
  43.     if(c == ':' || (cp=index(opts, c)) == NULL) {
  44.         ERR(": illegal option -- ", c);
  45.         if(argv[optind][++sp] == '\0') {
  46.             optind++;
  47.             sp = 1;
  48.         }
  49.         return('?');
  50.     }
  51.     if(*++cp == ':') {
  52.         if(argv[optind][sp+1] != '\0')
  53.             optarg = &argv[optind++][sp+1];
  54.         else if(++optind >= argc) {
  55.             ERR(": option requires an argument -- ", c);
  56.             sp = 1;
  57.             return('?');
  58.         } else
  59.             optarg = argv[optind++];
  60.         sp = 1;
  61.     } else {
  62.         if(argv[optind][++sp] == '\0') {
  63.             sp = 1;
  64.             optind++;
  65.         }
  66.         optarg = NULL;
  67.     }
  68.     return(c);
  69. }
  70.  
  71. char name[] = NAME;
  72.  
  73. static ERR(s, c)
  74. char s[];
  75. int c;
  76. {
  77.     extern int strlen(), write();
  78.     char errbuf[3];
  79.  
  80.     if(opterr){
  81.     errbuf[0] = c; errbuf[1] = '\r'; errbuf[2] = '\n';
  82.     write(2, name, (unsigned)strlen(name));
  83.     write(2, s, (unsigned)strlen(s));
  84.     write(2, errbuf, 3);}
  85. }
  86.